/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

define(['jquery', 'jquery-migrate', 'bootstrap', 'bootbox', 'bootstrap-datetimepicker', 'jquery-validation', 'jquery-validation-additional',
        'custom/zh_validator','datatables', 'dt_datatables', 'jquery.blockui', 'jquery.cokie', 'jquery-serializejson',
        'jquery.form', 'select2', 'uniform', 'fancybox', 'coreapp'], function ($) {
    if (App.isIE8()) {
        $('#page-sidebar-menu').removeClass('collapse');
    }
    // chinese
    bootbox.setDefaults({locale: 'zh_CN'});
    (function ($) {
        $.fn.datetimepicker.dates['zh-CN'] = {
            days       : ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort  : ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin    : ["日", "一", "二", "三", "四", "五", "六", "日"],
            months     : ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            today      : "今日",
            suffix     : [],
            meridiem   : ["上午", "下午"]
        };
    }(jQuery));
    (function ($) {
        "use strict";
        $.extend($.fn.select2.defaults, {
            formatNoMatches      : function () {
                return "没有找到匹配项";
            },
            formatInputTooShort  : function (input, min) {
                var n = min - input.length;
                return "请再输入" + n + "个字符";
            },
            formatInputTooLong   : function (input, max) {
                var n = input.length - max;
                return "请删掉" + n + "个字符";
            },
            formatSelectionTooBig: function (limit) {
                return "你只能选择最多" + limit + "项";
            },
            formatLoadMore       : function (pageNumber) {
                return "加载结果中…";
            },
            formatSearching      : function () {
                return "搜索中…";
            }
        });
    })(jQuery);
    var handleDatetimePicker = function () {

        var $datepicker = $('.date-picker');
        if ($datepicker.length > 0) {
            require(['bootstrap-datepicker', 'bootstrap-datepicker-zh'], function () {
                $datepicker.datepicker({
                    language : 'zh-CN',
                    rtl      : App.isRTL(),
                    autoclose: true
                });
                $('body').removeClass("modal-open");
            })
        }

        $(".form_datetime").datetimepicker({
            language      : 'zh-CN',
            autoclose     : true,
            isRTL         : App.isRTL(),
            format        : "yyyy-mm-dd hh:ii",
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left")
        });

        $(".form_advance_datetime").datetimepicker({
            language      : 'zh-CN',
            isRTL         : App.isRTL(),
            format        : "yyyy-mm-dd hh:ii",
            autoclose     : true,
            todayBtn      : true,
            startDate     : "2013-02-14 10:00",
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
            minuteStep    : 10
        });

        $(".form_meridian_datetime").datetimepicker({
            language      : 'zh-CN',
            isRTL         : App.isRTL(),
            format        : "yyyy-mm-dd hh:ii",
            showMeridian  : true,
            autoclose     : true,
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
            todayBtn      : true
        });

        $('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
    };

    handleDatetimePicker();

    var formvalidator = function (rule, formId) {
        var form = $('#' + formId);
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);

        (function ($) {
            $.extend($.validator.messages, {
                required   : "必须填写",
                remote     : "请修正此栏位",
                email      : "请输入有效的电子邮件",
                url        : "请输入有效的网址",
                date       : "请输入有效的日期",
                dateISO    : "请输入有效的日期 (YYYY-MM-DD)",
                number     : "请输入正确的数字",
                digits     : "只可输入数字",
                creditcard : "请输入有效的信用卡号码",
                equalTo    : "你的输入不相同",
                extension  : "请输入有效的后缀",
                maxlength  : $.validator.format("最多 {0} 个字"),
                minlength  : $.validator.format("最少 {0} 个字"),
                rangelength: $.validator.format("请输入长度为 {0} 至 {1} 之間的字串"),
                range      : $.validator.format("请输入 {0} 至 {1} 之间的数值"),
                max        : $.validator.format("请输入不大于 {0} 的数值"),
                min        : $.validator.format("请输入不小于 {0} 的数值")
            });
        }(jQuery));

        var validator = function () {

            var zh_method = function () {
                jQuery.validator.addMethod("byteRangeLength", function (value, element, param) {
                    var length = value.length;
                    for (var i = 0; i < value.length; i++) {
                        if (value.charCodeAt(i) > 127) {
                            length++;
                        }
                    }
                    return this.optional(element) || ( length >= param[0] && length <= param[1] );
                }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
                jQuery.validator.addMethod("idcard", function (value, element) {
                    return this.optional(element) || validatorKit.checkIdCardNo(value);
                }, "请正确输入您的身份证号码");
                jQuery.validator.addMethod("username", function (value, element) {
                    return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
                }, "用户名只能包括中文字、英文字母、数字和下划线");
                jQuery.validator.addMethod("zh-mobile", function (value, element) {
                    var length = value.length;
                    return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value));
                }, "请正确填写您的手机号码");
                jQuery.validator.addMethod("zh-phone", function (value, element) {
                    var tel = /^(\d{3,4}-?)?\d{7,9}$/g;
                    return this.optional(element) || (tel.test(value));
                }, "请正确填写您的电话号码");
                jQuery.validator.addMethod("zh-postcode", function (value, element) {
                    var tel = /^[0-9]{6}$/;
                    return this.optional(element) || (tel.test(value));
                }, "请正确填写您的邮政编码");
            };

            return {
                zh_method: zh_method
            }
        }();

        $.validator.setDefaults({
            submitHandler: function (form) {
                form.submit();
            }
        });

        validator.zh_method();

        form.validate({
            errorElement  : 'span', //default input error message container
            errorClass    : 'help-block', // default input error message class
            focusInvalid  : false, // do not focus the last invalid input
            errorPlacement: function (error, element) { // render error placement for each input type
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },
            invalidHandler: function (event, validator) { //display error alert on form submit
                if (success) {
                    success.hide();
                }
                error.show();
                App.scrollTo(error, -200);
            },

            highlight: function (element) { // hightlight error inputs
                $(element)
                    .closest('.form-group').addClass('has-error'); // set error class to the control group
            },

            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                    .closest('.form-group').removeClass('has-error'); // set error class to the control group
            },

            success      : function (label) {
                label
                    .closest('.form-group').removeClass('has-error'); // set success class to the control group
            },
            rules        : rule,
            submitHandler: function (form) {
                if (success) {
                    success.hide();
                }

                error.hide();
                form.submit();
            }
        });
    };

    var defaultTableOptions = {
        'bLengthChange'  : false,
        'bFilter'        : false, //搜索栏
        'bSort'          : true, //是否支持排序功能
        'bInfo'          : true, //显示表格信息
        'bStateSave'     : true, //保存状态到cookie
        'bAutoWidth'     : false,
        'bPaginate'      : true,
        'sPaginationType': 'bootstrap_full_number',
        'bProcessing'    : false,
        'bServerSide'    : true,
        'iDisplayLength' : 10,
        'oLanguage'      : {
            'sLengthMenu'  : "<span>每页显示</span> _MENU_",
            'sZeroRecords' : "对不起，查询不到任何相关数据",
            'sInfo'        : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            'sInfoEmpty'   : "没有任何数据可以显示",
            'sInfoFiltered': "(数据表中共为 _MAX_ 条记录)",
            'sProcessing'  : "正在加载中...",
            'sSearch'      : "<span>搜索：</span> _INPUT_",
            'oPaginate'    : {
                'sFirst'   : "首页",
                'sPrevious': "< ",
                'sNext'    : "> ",
                'sLast'    : "尾页 "
            }
        }, //多语言配置
        'bJQueryUI'      : false,
        'aLengthMenu'    : [
            [10, 25, 50],
            ["10条", "25条", "50条"]
        ],
        // 序号最终实现
        'fnRowCallback'  : function (nRow, aData, iDisplayIndex) {
            var oSettings = this.fnSettings();
            $("td:eq(1)", nRow).html(oSettings._iDisplayStart + iDisplayIndex + 1);
            return nRow;
        },
        'fnDrawCallback' : function (oSettings) {
            var $table = $('#' + oSettings.sTableId);

            App.initUniform('input:checkbox', $table);

            $table.find('.tip').tooltip();

            var $fancybox = $table.find(".fancybox-button");
            if ($fancybox.length > 0) {
                $fancybox.fancybox({
                        groupAttr  : 'data-rel',
                        prevEffect : 'none',
                        nextEffect : 'none',
                        overlayShow: false,
                        closeBtn   : true,
                        helpers    : {
                            title: {
                                type: 'inside'
                            }
                        }}
                );
            }
        }
    };

    var uploader = function (options, uploaderId) {

        require(['uploadify'], function () {
            var defaultUploaderOptions = {
                'debug'           : false,
                'height'          : 38,
                'auto'            : true,
                'swf'             : g.ctx + 'static/scripts/plugins/uploadify/uploadify.swf',
                'uploader'        : g.ctx + 'file/up',
                'width'           : 60,
                'buttonText'      : '附件',
                'fileTypeExts'    : '*.jpg;*.jpge;*.gif;*.png',
                'fileTypeDesc'    : '图片',
                'sizeLimit'       : '5MB',
                'wmode'           : 'transparent',
                'hideButton'      : true,
                'itemTemplate'    : '<div id="${fileID}" class="uploadify-queue-item"></div>',
                'queueSizeLimit'  : 1,
                //每次更新上载的文件的进展
                'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
                }, //选择上传文件后调用
                'onSelect'        : function (file) {
                },
                //返回一个错误，选择文件的时候触发
                'onSelectError'   : function (file, errorCode, errorMsg) {
                    console.log(file);
                    var $fileupload = $('#' + uploaderId);
                    switch (errorCode) {
                        case -100:
                            bootbox.alert("上传的文件数量已经超出系统限制的" + $fileupload.uploadify('settings', 'queueSizeLimit') + "个文件！");
                            break;
                        case -110:
                            bootbox.alert("文件 [" + file.name + "] 大小超出系统限制的" + $fileupload.uploadify('settings', 'fileSizeLimit') + "大小！");
                            break;
                        case -120:
                            bootbox.alert("文件 [" + file.name + "] 大小异常！");
                            break;
                        case -130:
                            bootbox.alert("文件 [" + file.name + "] 类型不正确！");
                            break;
                    }
                },
                //检测FLASH失败调用
                'onFallback'      : function () {
                    bootbox.alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
                },
                'onUploadComplete': function () {

                },
                //上传到服务器，服务器返回相应信息到data里
                'onUploadSuccess' : function (file, data, response) {
                    var jsonData = eval('(' + data + ')');
                    if (jsonData['status'] == 'OK') {
                        var attachement_path = jsonData['data'];
                        $('#picture').val(attachement_path);

                        var $boxPicture = $('#box_picture');
                        $boxPicture.attr('href', g.ctx + attachement_path);
                        $boxPicture.find('img').attr('src', g.ctx + attachement_path.replace('.', '.thumbnail.'));

                        $('#show_picture').slideDown();

                    }
                }
            };
            var opts = $.extend(defaultUploaderOptions, options);
            return  $("#" + uploaderId).uploadify(opts);
        });

    };

    var single_uploader = function (options, uploaderId) {
        require(['uploadify'], function () {

            var singleDefaultOpts = {
                'debug'           : false,
                'height'          : 38,
                'auto'            : true,
                'swf'             : g.ctx + 'static/scripts/plugins/uploadify/uploadify.swf',
                'uploader'        : g.ctx + 'file/up',
                'width'           : 60,
                'buttonText'      : '附件',
                'fileTypeExts'    : '*.jpg;*.jpge;*.gif;*.png',
                'fileTypeDesc'    : '图片',
                'sizeLimit'       : '5MB',
                'wmode'           : 'transparent',
                'hideButton'      : true,
                'itemTemplate'    : '<div id="${fileID}" class="uploadify-queue-item"></div>',
                'queueSizeLimit'  : 1,
                //每次更新上载的文件的进展
                'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
                }, //选择上传文件后调用
                'onSelect'        : function (file) {
                },
                //返回一个错误，选择文件的时候触发
                'onSelectError'   : function (file, errorCode, errorMsg) {
                    var $fileupload = $('#' + uploaderId);
                    switch (errorCode) {
                        case -100:
                            bootbox.alert("上传的文件数量已经超出系统限制的" + $fileupload.uploadify('settings', 'queueSizeLimit') + "个文件！");
                            break;
                        case -110:
                            bootbox.alert("文件 [" + file.name + "] 大小超出系统限制的" + $fileupload.uploadify('settings', 'fileSizeLimit') + "大小！");
                            break;
                        case -120:
                            bootbox.alert("文件 [" + file.name + "] 大小异常！");
                            break;
                        case -130:
                            bootbox.alert("文件 [" + file.name + "] 类型不正确！");
                            break;
                    }
                },
                //检测FLASH失败调用
                'onFallback'      : function () {
                    bootbox.alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
                },
                'onUploadComplete': function () {
                },
                //上传到服务器，服务器返回相应信息到data里
                'onUploadSuccess' : function (file, data, response) {
                    var current_dom = $('#' + file.id);
                    var jsonData = eval('(' + data + ')');
                    if (jsonData['status'] == 'OK') {
                        var $fileinput = current_dom.closest('div.fileinput');
                        var $input_val = $fileinput.find('input:hidden');

                        var attachement_path = jsonData['data'];
                        $input_val.val(attachement_path);

                        var $preview = $fileinput.find('div.fileinput-preview');
                        var img_html = '<a href="' + g.ctx + attachement_path + '" class="thumbnail fancybox-button">' +
                            '<img src="' + g.ctx + attachement_path.replace('.', '.thumbnail.') + '" alt=""></a>';
                        $preview.html(img_html);

                        var $btns = $fileinput.find('div.fileinput-btn');
                        var $remove_btn = $btns.find('a.fileinput-remove');
                        if ($remove_btn) {
                            $remove_btn.remove();
                        }
                        $btns.append('<a href="#" data-data="' + attachement_path + '" class="btn default fileinput-exists fileinput-remove">删除图片</a>');
                        var $fancybox = $fileinput.find('.fancybox-button');
                        if ($fancybox.size() > 0) {
                            $fancybox.fancybox({
                                groupAttr : 'data-rel',
                                prevEffect: 'none',
                                nextEffect: 'none',
                                closeBtn  : true,
                                helpers   : {
                                    title: {
                                        type: 'inside'
                                    }
                                }
                            });
                        }
                    }
                }
            };
            var opts = $.extend(singleDefaultOpts, options);
            return  $("#" + uploaderId).uploadify(opts);
        });
    };

    $('div.fileinput').on('click', 'a.fileinput-remove', function () {
        var $this = $(this);
        var $fileinput = $this.closest('div.fileinput');
        var path = $this.attr('data-data');
        if (path) {
            bootbox.confirm({
                title   : '温馨提示',
                message : '您确定删除这张图片么？',
                callback: function (r) {
                    if (r) {
                        $.post(g.ctx + 'file/remove', {'DATA': path}, function (rst) {
                            if (rst.status == 'OK') {
                                var $val_input = $fileinput.find('input:hidden');
                                $val_input.val('');
                                var $preview = $fileinput.find('div.fileinput-preview>a');
                                $preview.remove();
                                $this.remove();
                            } else {
                                bootbox.alert('删除图片失败!')
                            }
                        })
                    }
                }
            });
        }
    });

    var listtable = function (options, domId) {
        if (!jQuery().dataTable) {
            return;
        }
        var $dt = $('#' + domId);
        if (!options['sAjaxSource']) {
            options['sAjaxSource'] = $dt.attr('data-sAjaxSource');
        }
        var opts = $.extend(defaultTableOptions, options);

        var $table = $dt.dataTable(opts);


        var $OTable = $('#' + domId + "_wrapper");
        $OTable.find('.dataTables_filter input[type=text]').attr('placeholder', '请输入检索...');
        $OTable.find('.dataTables_length select').select2({
            minimumResultsForSearch: "-1"
        });
        return $table;
    };

    var navactive = function (module) {

        var $m = $('#' + module);
        $m.addClass('active');
//
        var parents = $m.parents('li');
        if (parents) {
            parents.addClass('active');
        }
    };

    var attr_data = function ($ele) {
        var title = $ele.attr('data-title');
        if (!title) {
            title = '温馨提示';
        }
        var message = $ele.attr('data-message');
        if (!message) {
            message = '您确定要删除该条数据么？'
        }

        var action = $ele.attr('data-action');
        return {action: action, title: title, message: message};
    };


    ////// Dom Event On //////

    // table check all event.
    var $table = $('.table');
    $table.on('click', 'input.checkall', function () {
        var table = $(this).parents('table');
        if (!$(this).is(':checked')) {
            table.find('.checker span').removeClass('checked').find('input[type=checkbox]').attr('checked', false);
            table.find('tbody>tr').removeClass('row_selected');
        } else {
            table.find('.checker span').addClass('checked').find('input[type=checkbox]').attr('checked', true);
            table.find('tbody>tr').addClass('row_selected');
        }
    });
    // sigle colomn check event.
    $table.on('click', 'td>div.checker>span>input[type=checkbox]', function () {
        var tr = $(this).closest('tr');
        if (!$(this).is(':checked')) {
            tr.find('.checker span').removeClass('checked').find('input[type=checkbox]').attr('checked', false);
            tr.removeClass('row_selected');
        } else {
            tr.find('.checker span').addClass('checked').find('input[type=checkbox]').attr('checked', true);
            tr.addClass('row_selected');
        }
    });
    $table.on('click', 'a[data-hook="remove-action"]', function () {
        var $this = $(this);
        var data = attr_data($this);
        var action = data.action;
        if (action) {

            var $datatables = $this.parents('table.table').dataTable();

            bootbox.confirm({
                title   : data.title,
                message : data.message,
                callback: function (r) {
                    if (r) {
                        $.post(action, function (rst) {
                            if (rst.status == 'OK') {
                                $datatables.fnDraw();
                            }
                        })
                    }
                }
            });
        }
        return false;
    });

    $table.on('click', 'a[data-hook="stop-action"]', function () {
        var $this = $(this);
        var data = attr_data($this);
        var action = data.action;
        if (action) {

            var $datatables = $this.parents('table.table').dataTable();

            bootbox.confirm({
                title   : data.title,
                message : data.message,
                callback: function (r) {
                    if (r) {
                        $.post(action, function (rst) {
                            if (rst.status == 'OK') {
                                $datatables.fnDraw();
                            }
                        })
                    }
                }
            });
        }
        return false;
    });

    // Batch Delete.
    var $table_toolbar = $('.table-toolbar');
    $table_toolbar.on('click', 'a.batchdelete', function () {
        var $this = $(this);
        var data = attr_data($this);
        var action = data.action;
        if (action) {
            var data_pk = $this.attr('data-pkcolumn');
            if (!data_pk) {
                data_pk = 'id';
            }
            var title = data.title;
            var message = data.message;
            var $datatables = $($this.attr('data-tables')).dataTable();
            var aTrs = $datatables.fnGetNodes();
            var selectIds = [];
            for (var i = 0; i < aTrs.length; i++) {
                if ($(aTrs[i]).hasClass('row_selected')) {
                    selectIds.push($datatables.fnGetData(aTrs[i])[data_pk]);
                }
            }
            if (selectIds.length <= 0) {
                return;
            } else {
                bootbox.confirm({
                    title   : title,
                    message : message,
                    callback: function (r) {
                        if (r) {
                            $.post(action, {'DATA': selectIds.join()}, function (rst) {
                                if (rst.status == 'OK') {
                                    $datatables.fnDraw();
                                }
                            })
                        }
                    }
                });
            }
        }
        return false;
    });

    // Batch stop.
    $table_toolbar.on('click', 'a.batchstop', function () {
        var $this = $(this);
        var data = attr_data($this);
        var action = data.action;
        if (action) {
            var data_pk = $this.attr('data-pkcolumn');
            if (!data_pk) {
                data_pk = 'id';
            }
            var title = data.title;
            var message = data.message;
            var $datatables = $($this.attr('data-tables')).dataTable();
            var aTrs = $datatables.fnGetNodes();
            var selectIds = [];
            for (var i = 0; i < aTrs.length; i++) {
                if ($(aTrs[i]).hasClass('row_selected')) {
                    selectIds.push($datatables.fnGetData(aTrs[i])[data_pk]);
                }
            }
            if (selectIds.length <= 0) {
                return;
            } else {
                bootbox.confirm({
                    title   : title,
                    message : message,
                    callback: function (r) {
                        if (r) {
                            $.post(action, {'DATA': selectIds.join()}, function (rst) {
                                if (rst.status == 'OK') {
                                    $datatables.fnDraw();
                                }
                            })
                        }
                    }
                });
            }
        }
        return false;
    });

    var $page = $('.page-content');
    $page.on('click', 'a[data-hook="ajax-action"]', function () {
        var $this = $(this);
        var data = attr_data($this);
        var action = data.action;
        if (action) {
            bootbox.confirm({
                title   : data.title,
                message : data.message,
                callback: function (r) {
                    if (r) {
                        $.get(action, function (rst) {
                            if (rst.status == 'OK') {
                                bootbox.alert('操作成功!');
                            } else {
                                bootbox.alert(rst.message)
                            }
                        })
                    }

                }
            });
        }
        return false;
    });
    $page.on('click', 'a[data-hook="remove_picture"]', function (e) {
        e.preventDefault();
        var $this = $(this);
        var path = $this.attr('data-data');
        var target = $this.attr('data-target');
        if (path) {
            bootbox.confirm({
                title   : '温馨提示',
                message : '您确定删除这张图片么？',
                callback: function (r) {
                    if (r) {
                        $.post(g.ctx + 'file/remove', {'DATA': path}, function (rst) {
                            if (rst.status == 'OK') {
                                var values = $(target).val();
                                if (values) {
                                    var items = values.split(',');
                                    var new_items = [];
                                    for (var idx = 0; idx < items.length; idx++) {
                                        var item = items[idx];
                                        if (item == '' || item == path)
                                            continue;
                                        new_items.push(item);
                                    }
                                    $(target).val(new_items.join(','));
                                    var closest = $this.closest('.picture');
                                    closest.slideUp();
                                    closest.remove();
                                }
                            } else {
                                bootbox.alert('删除图片失败!')
                            }
                        })
                    }
                }
            });
        }
    });

    App.init();

    var template_html = '{{#each this}}<option value="{{id}}">{{text}}</option>{{/each}}';
    var tpl_select =  Handlebars.compile(template_html);
    var option_tpl = function (data) {
        return tpl_select(data);
    };

    $.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings, sNewSource, fnCallback, bStandingRedraw) {
        if ($.fn.dataTable.versionCheck) {
            var api = new $.fn.dataTable.Api(oSettings);

            if (sNewSource) {
                api.ajax.url(sNewSource).load(fnCallback, !bStandingRedraw);
            } else {
                api.ajax.reload(fnCallback, !bStandingRedraw);
            }
            return;
        }

        if (sNewSource !== undefined && sNewSource !== null) {
            oSettings.sAjaxSource = sNewSource;
        }

        // Server-side processing should just call fnDraw
        if (oSettings.oFeatures.bServerSide) {
            this.fnDraw();
            return;
        }

        this.oApi._fnProcessingDisplay(oSettings, true);
        var that = this;
        var iStart = oSettings._iDisplayStart;
        var aData = [];

        this.oApi._fnServerParams(oSettings, aData);

        oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function (json) {
            /* Clear the old information from the table */
            that.oApi._fnClearTable(oSettings);

            /* Got the data - add it to the table */
            var aData = (oSettings.sAjaxDataProp !== "") ?
                that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;

            for (var i = 0; i < aData.length; i++) {
                that.oApi._fnAddData(oSettings, aData[i]);
            }

            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

            that.fnDraw();

            if (bStandingRedraw === true) {
                oSettings._iDisplayStart = iStart;
                that.oApi._fnCalculateEnd(oSettings);
                that.fnDraw(false);
            }

            that.oApi._fnProcessingDisplay(oSettings, false);

            /* Callback user function - for event handlers etc */
            if (typeof fnCallback == 'function' && fnCallback !== null) {
                fnCallback(oSettings);
            }
        }, oSettings);
    };

    var $switch = $("input.make-switch");
    if ($switch.length > 0) {
        require(['bootstrap-switch'], function () {
            $switch.each(function () {
                $(this).bootstrapSwitch();
            });
        });
    }


    var editor = function (editor_id, br) {
        var newlineTag = br ? 'br' : 'p';
        var $KEditor;
        require(['kindeditor', 'kindeditor-lang'], function () {
            KindEditor.options.cssData = 'body { font-size: 14px; } .ke-content img {width: 100%;} .ke-content img.ke-emoticons {width: auto;}';
            $KEditor = KindEditor.create(editor_id, {
                width                : '320px',
                minWidth             : '320px',
                minHeight            : '480px',
                height               : '480px',
                fontSizeTable        : ['12px', '14px', '16px', '18px', '24px', '32px'],
                resizeType           : 1,
                allowPreviewEmoticons: false,
                syncType             : 'form',
                allowImageUpload     : false,
                newlineTag           : newlineTag,
                uploadJson           : g.ctx + 'file/editor',
                items                : [
                    'bold', 'italic', 'underline', '|', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'multiimage', 'baidumap',
                    '|', 'removeformat', 'forecolor', 'hilitecolor'],
                'afterBlur'          : function () {
                    //编辑器失去焦点时直接同步，可以取到值
                    this.sync();
                }
            });
        });
        return $KEditor;
    };

    return {
        navactive      : navactive,
        listtable      : listtable,
        uploader       : uploader,
        single_uploader: single_uploader,
        formvalidator  : formvalidator,
        autono         : { //自增长序号
            'mDataProp'      : null,
            'sDefaultContent': 1,
            'bSortable'      : false
        },
        columns        : {
            status: {

            },
            active: {

            }
        },
        checkall       : {
            'sTitle'         : "<input type='checkbox' class='checkall'/>",
            'mDataProp'      : null,
            'sDefaultContent': "<input type='checkbox'/>",
            'bSortable'      : false
        },
        app            : App,
        initEditor     : editor,
        selectOption   : option_tpl
    }
});